package com.xiangxiao.rpan.utils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2023/10/20 17:40
 */
public class ClassUtils {

  /**
   * 获取指定类的超类的泛型参数类型, 只获取第一个泛型类型(父类)
   * @param   clazz
   *          泛型类
   * @return  泛型类型
   */
  public static Class<?> getClassFirstGenericsParam(Class<?> clazz) {
    Type type = clazz.getGenericSuperclass();
    if (type instanceof ParameterizedType) {
      ParameterizedType pType = (ParameterizedType) type;
      Type actualTypeArgument = pType.getActualTypeArguments()[0];
      return (Class<?>) actualTypeArgument;
    };
    return null;
  }

  /**
   * 获取指定类的泛型参数类型, 只获取第一个泛型类型(当前类)
   * */
  public static Class<?> getClassFirstParam(Object instance) {
    Class clazz = instance.getClass();
    Type type = clazz.getGenericSuperclass();
    Type actualTypeArgument = ((ParameterizedType) type).getActualTypeArguments()[0];
    return (Class<?>) actualTypeArgument;
  }
}
